package com.snsoft.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.ComponentScan.Filter;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.FilterType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.view.InternalResourceViewResolver;

import com.snsoft.SpringConfigMark;
import com.snsoft.web.interceptor.EncodeInterceptor;
import com.snsoft.web.interceptor.LoginInterceptor;

/**
 * 
 * @author 慎伟康
 * 
 * @date 2017年11月26日 上午12:09:50
 * 
 * @Description TODO
 *    Spring MVC配置类
 * 
 * @Configuration
 *    声明配置类 
 * @EnableWebMvc
 *    启用Spring MVC
 * 
 * @ComponentScan
 *    启用组件扫描
 * @see basePackageClasses
 *    指定为包中所包含的类，这些类所在的包将会作为组件扫描的基础包。这种方法是类型安全的。
 * @see includeFilters
 *    只扫描与web相关的类：@Controller和@ControllerAdvice
 */
@Configuration
@EnableWebMvc
@ComponentScan(basePackageClasses = SpringConfigMark.class, includeFilters = { 
	@Filter(type = FilterType.ANNOTATION, value = {
	Controller.class, ControllerAdvice.class }) })
public class SpringMvcConfig extends WebMvcConfigurerAdapter {

	/**
	 * 配置JSP视图解析器
	 * @return
	 */
	@Bean
	public ViewResolver viewResolver(){
		InternalResourceViewResolver resolver = new InternalResourceViewResolver();
		resolver.setPrefix("/WEB-INF/views/");
		resolver.setSuffix(".jsp");
		resolver.setExposeContextBeansAsAttributes(true);
		return resolver;
	}
	
	/**
	 * 配置静态资源的处理
	 */
	@Override
	public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
		configurer.enable();//不拦截静态资源
	}

	/**
	 * 配置编码拦截器，没有使用注解用来自动扫描，所以需要手动配置
	 * @return
	 */
	@Bean
	public EncodeInterceptor encodeInterceptor(){
		return new EncodeInterceptor();
	}
	
	/**
	 * 配置登录拦截器，没有使用注解用来自动扫描，所以需要手动配置
	 * @return
	 */
	@Bean
	public LoginInterceptor loginInterceptor(){
		return new LoginInterceptor();
	}

	/**
	 * 注册拦截器，注册顺序就是拦截顺序。
	 * "/**"拦截所有文件夹及其子文件夹，能拦截"/user/login"
	 * "/*"只能拦截所有文件夹，无法拦截二级目录，不能拦截"/user/login"
	 */
	@Override
	public void addInterceptors(InterceptorRegistry registry) {
		super.addInterceptors(registry);
		registry.addInterceptor(encodeInterceptor()).addPathPatterns("/**");
		registry.addInterceptor(loginInterceptor()).addPathPatterns("/index.html");//主页
	}
}
